package com.fnd.servicechat.service.impl;

import com.fnd.servicechat.controller.dto.Result;
import com.fnd.servicechat.service.IFileOptionService;
import com.fnd.servicechat.util.FileUtils;
import com.fnd.servicechat.util.RandomUtil;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @Description 文件操作service实现
 * @Author Administrator
 * @Date 2019/11/15 14:54
 * @Version 1.0
 */
@Service
public class FileOptionServiceImpl implements IFileOptionService {
    private final static String FILE_STORE_PATH = "D://file"; //文件相对路径 TODO
    @Override
    public Result upload(MultipartFile file) {
        // 重命名文件，防止重名
        String filename = RandomUtil.getRandomUUID();  //保存的文件名称
        String originalFilename = file.getOriginalFilename();
        String fileSize = FileUtils.getFormatSize(file.getSize());
        // 截取文件的后缀名
        String suffix = "";
        if (originalFilename.contains(".")) {
            suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        }
        filename = filename + suffix;

//        System.out.println("存储路径为:" + FILE_STORE_PATH + "\\" + filename);
//        Path filePath = Paths.get(FILE_STORE_PATH, filename);
//        try {
//            Files.copy(file.getInputStream(), filePath);
//        } catch (Exception e) {
//            e.printStackTrace();
//            return new Result().error("文件上传发生错误！");
//        }
        File savefile = new File(FILE_STORE_PATH +"/"+ filename);
        if (!savefile.getParentFile().exists()) {
            savefile.getParentFile().mkdirs();
        }
        try {
            file.transferTo(savefile);
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return new Result().success()
                .setData("originalFilename", originalFilename)
                .setData("fileSize", fileSize)
                .setData("fileUrl", "/file/" + filename);

    }
}
